package cn.ante.pet.service.impl;

import cn.ante.basic.constant.BaseContants;
import cn.ante.basic.utils.BaiduAuditUtils;
import cn.ante.pet.mapper.PetDetailMapper;
import cn.ante.pet.mapper.PetMapper;
import cn.ante.pet.mapper.PetOnlineAuditLogMapper;
import cn.ante.pet.service.IPetService;
import cn.ante.pet.domain.Pet;
import cn.ante.pet.domain.PetDetail;
import cn.ante.pet.domain.PetOnlineAuditLog;
import cn.ante.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Nai
 * @since 2022-07-16
 */
@Service
public class PetServiceImpl extends BaseServiceImpl<Pet> implements IPetService {

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private PetDetailMapper petDetailMapper;

    @Autowired
    private PetOnlineAuditLogMapper petOnlineAuditLogMapper;

    @Override
    public void add(Pet pet) {
        petMapper.add(pet);
        PetDetail petDetail = pet.getPetDetail();
        if (petDetail != null){
            petDetail.setPetId(pet.getId());
            petDetailMapper.add(petDetail);
        }
    }

    @Override
    public void offSale(Long[] ids) {
        petMapper.offSale(ids);
    }

    @Override
    public void onSale(Long[] ids) {
        // 遍历数组
        for (Long id : ids){
            Pet pet = petMapper.loadById(id);

            // 记录审核失败日志
            StringBuffer stringBuffer = new StringBuffer();

            if (!BaiduAuditUtils.TextCensor(pet.getName())){
                stringBuffer.append("名称审核失败，名称不合法" + pet.getName());
            }
            for (String filePath:pet.getResources().split(",")){
            if (!BaiduAuditUtils.ImgCensor(filePath.getBytes())){
                stringBuffer.append("图片审核失败，图片不合法" + BaseContants.ImageAudit.CALL_ADDRESS + filePath);
            }
            }
            if (stringBuffer.length() > 0){
                PetOnlineAuditLog petOnlineAuditLog = new PetOnlineAuditLog();
                petOnlineAuditLog.setState(0);
                petOnlineAuditLog.setPetId(id);
                petOnlineAuditLog.setAuditTime(new Date());
                petOnlineAuditLog.setNote(stringBuffer.toString());
                petOnlineAuditLogMapper.add(petOnlineAuditLog);
            }
            petMapper.onSale(id);
        }
    }

    @Override
    public Pet loadByIdDetail(Long id) {
        return petMapper.loadByIdDetail(id);
    }
}
